﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;

/// <summary>
///Bulletin 的摘要说明
/// </summary>
public partial class Bulletin
{
    public enum type { 前台 = 1 }
    public static Bulletin Get(int id)
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            return context.Bulletin.FirstOrDefault(row => row.ID == id);
        }
    }

    public static List<Bulletin> GetAll()
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            return context.Bulletin.OrderByDescending(row => row.Rank).ToList();
        }
    }

    public static List<Bulletin> GetAllByConditon(string Key, string TimeFrom, string TimeTo, int Type, int Skip, int Take)
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            var query = from q in context.Bulletin
                        select q;
            if (!string.IsNullOrEmpty(Key))
                query = query.Where(row => row.Title.Contains(Key) || row.Detail.Contains(Key));
            if (!string.IsNullOrEmpty(TimeFrom))
                query = query.Where(row => row.AddTime >= DongDong.Common.Misc.ConvertToDateTime(TimeFrom));
            if (!string.IsNullOrEmpty(TimeTo))
                query = query.Where(row => row.AddTime <= DongDong.Common.Misc.ConvertToDateTime(TimeTo));
            if (Type != 0)
                query = query.Where(row => row.Type == Type);
            if (Skip != 0)
                query = query.Skip(Skip);
            if (Take != 0)
                query = query.Take(Take);
            return query.OrderByDescending(row => row.Rank).ToList();
        }
    }

    public void Add()
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            context.Bulletin.InsertOnSubmit(this);
            context.SubmitChanges();
        }
    }

    public void Update()
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            this.GetType().GetMethod("Detach").Invoke(this, null);
            var tbl = context.GetTable<Bulletin>();
            tbl.Attach(this);
            context.Refresh(RefreshMode.KeepCurrentValues, this);
            context.SubmitChanges();
        }
    }

    public static void Delete(int id)
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            var objItem = context.Bulletin.FirstOrDefault(row => row.ID == id);
            if (objItem == null)
                return;
            context.Bulletin.DeleteOnSubmit(objItem);
            context.SubmitChanges();
        }
    }
}